import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '~/vuex/index'
import routes from './routes'

Vue.use(VueRouter);

const router = new VueRouter({
  history: true,
  saveScrollPosition: true,
  routes
});

const auth_filter = (to, from, next) => {
  let requireNoLogin = to.meta.requireUnAuth || false

  //判断是否登录的先注释

  let authorized = store.getters.user_authorized

  // let authorized = true

  if (authorized) {
    if (requireNoLogin) {
      next('/')
    } else {
      next()
    }
  } else {
    if (requireNoLogin) {
      next()
    } else {
      next('/login')
    }
  }


}

const serverErrorHandle = (to, from, next) => {
  let toErrorPage = store.getters.error_occurred
  let isErrorPage = to.meta.isErrorPage || false

  if (!isErrorPage) store.dispatch('toErrorPage', '')

  if (toErrorPage != '') {
    next(toErrorPage)
  } else {
    next()
  }
}

router.beforeEach((to, from, next) => {
  let requireNoLogin = to.meta.requireUnAuth || false
  let appInitialized = store.getters.app_initialized

  if (requireNoLogin) {
    next()
    return
  }


  store.watch((state, getters) => {
    return getters.error_occurred
  }, () => {
    serverErrorHandle(to, from, next)
  })

  if (!appInitialized) {
    let w = store.watch((state, getters) => {
      return getters.app_initialized
    }, () => {
      auth_filter(to, from, next)
    })
    store.dispatch('app_initialize')
  } else {
    auth_filter(to, from, next)
  }
});


export default router;
